<template>
  <div>
    <!--    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline" v-hasPermi="['sa:report:query']">-->
    <!--      <el-form-item label="创建人" prop="createBy">-->
    <!--        <el-input v-model.trim="queryParams.createBy" size="small" clearable :minlength="100" placeholder="请输入创建人"></el-input>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item>-->
    <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchHandler">查询</el-button>-->
    <!--        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

    <div class="grid-content bg-purple">
      <el-button type="primary" icon="el-icon-refresh" size="mini" v-hasPermi="['after:workorder:problem:query']"
                 @click="searchHandler">刷新
      </el-button>
      <el-button
        plain
        type="primary"
        size="mini"
        icon="el-icon-plus"
        v-if="(workorder.status === '进行中' && $auth.hasPermi('after:workorder:problem:add')) || $auth.hasPermi('after:workorder:edit')"
        @click="openDialog(null)"
      >增加
      </el-button>
    </div>

    <div v-if="device !== 'mobile'">
      <el-table
        ref="tableRef"
        :data="tableData"
        v-loading="loading"
        highlight-current-row
        max-height="500"
        v-horizontal-scroll="'auto'"
        style="width: 100%;margin-top: 10px;">
        <!--        <el-table-column type="expand" label="展开">-->
        <!--          <template slot-scope="scope">-->
        <!--            <div class=" img-box" v-if="scope.row.image.length > 2">-->
        <!--              <div v-for="(url, i) in (scope.row.image.split(','))" :key="i">-->
        <!--                <el-image lazy style="width: 160px; height: auto;" fit="contain" :src="env + url"-->
        <!--                          @click="handlePictureCardPreview(url)">-->
        <!--                  <div slot="error" class="image-slot">-->
        <!--                    <i class="el-icon-picture-outline"></i>-->
        <!--                  </div>-->
        <!--                </el-image>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--            <div class=" img-box flex justify-content" v-else>无</div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          property="content"
          label="问题汇总"
          align="center"
        />
        <el-table-column
          property="remark"
          label="备注"
          align="center"
        />
        <el-table-column property="image" label="查看图片" align="center" width="100">
          <template slot-scope="scope">
            <div class=" img-box" v-if="scope.row.image.length > 2">
              <div>
                <el-image
                  style="width: 80px; height: auto;"
                  fit="contain"
                  :src="env + scope.row.image.split(',')[0]"
                  :preview-src-list="scope.row.image.split(',').map(i=> (env + i))"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </div>
            <div class=" img-box justify-content" v-else>无</div>
          </template>
        </el-table-column>
        <el-table-column
          property="createBy"
          label="操作人"
          align="center"
        />
        <el-table-column
          property="createTime"
          label="操作时间"
          align="center"
        />
        <el-table-column
          label="操作"
          align="center"
          v-if="(($auth.hasPermi('after:workorder:problem:edit') || $auth.hasPermi('after:workorder:problem:remove')) && workorder.status === '进行中') || $auth.hasPermi('after:workorder:edit')"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              v-if="$auth.hasPermi('after:workorder:problem:edit') || $auth.hasPermi('after:workorder:edit')"
              @click="openDialog(scope.row)"
            >修改
            </el-button>
            <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              title="确定删除吗？"
              @confirm="deleteHandler(scope.row)"
            >
              <el-button slot="reference" icon="el-icon-delete"
                         v-if="$auth.hasPermi('after:workorder:problem:remove') || $auth.hasPermi('after:workorder:edit')"
                         type="text" style="margin-left: 10px">删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <div v-else class="infinite-box" style="max-height: 500px;overflow: auto;">
      <ul class="infinite-list" v-infinite-scroll="handleLoad">
        <li v-for="item in tableData" :key="item.id" class="infinite-list-item">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ item.createTime }}</span>
              <div style="float: right;">
                <el-button type="text"
                           v-if="$auth.hasPermi('after:workorder:work:edit') || $auth.hasPermi('after:workorder:edit')"
                           @click="openDialog(item)" style="padding: 3px 0;">修改
                </el-button>
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                               @confirm="deleteHandler(item)">
                  <el-button slot="reference"
                             v-if="$auth.hasPermi('after:workorder:work:remove') || $auth.hasPermi('after:workorder:edit')"
                             type="text" style="margin-left: 10px;padding: 3px 0;">删除
                  </el-button>
                </el-popconfirm>
              </div>
            </div>
            <div class=" cus_text">
              <div class="flex">
                <span>工作日志: </span>
                <span class="flex-1">{{ item.content }}</span>
              </div>
              <div class="flex">
                <span>操作人: </span>
                <span class="flex-1">{{ item.createBy }}</span>
              </div>
              <div class="flex" v-if="item.remark">
                <span>备注: </span>
                <span class="flex-1">{{ item.remark }}</span>
              </div>
              <div class="flex" v-if="item.image.length > 2">
                <span>查看图片: </span>
                <div class="flex-1">
                  <el-image
                    style="width: 50px; height: auto;"
                    fit="contain"
                    :src="env + item.image.split(',')[0]"
                    :preview-src-list="item.image.split(',').map(i=> (env + i))"
                  >
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
              </div>
            </div>
          </el-card>
        </li>
      </ul>

      <div v-if="loading" style="text-align: center;color: #909399;"><i class="el-icon-loading"></i> 正在加载</div>
      <div v-else-if="tableData.length <= 0" style="text-align: center;color: #909399;">暂无数据</div>
      <div v-else-if="!queryParams.hasNextPage" style="text-align: center;color: #909399;">暂无更多数据</div>

      <el-backtop target=".infinite-box"></el-backtop>
    </div>

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
      :fullscreen="device === 'mobile'"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        class="demo-form"
        :label-position="device === 'mobile' ? 'top' : 'right'"
      >
        <el-form-item label="问题汇总" prop="content">
          <el-input v-model.trim="form.content" type="textarea" :maxlength="500" placeholder="请输入问题汇总"
                    :autosize="{ minRows: 2 }"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="250" placeholder="请输入备注"
                    :autosize="{ minRows: 2 }"/>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload class="upload-demo" ref="upload" action="#" :limit="9" :on-change="handleChange"
                     :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" accept=".jpg,.jpeg,.png,.gif"
                     list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="uploadLoading" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="imgDialogVisible" width="800px" :fullscreen="device === 'mobile'">
      <img width="100%" height="auto" style="object-fit: contain;" :src="imgDialogUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import {
  addDataApi,
  deleteDataApi,
  getDataListApi,
  updateDataApi,
  uploadImgApi
} from "@/api/after/workorder/problemSummary";
import {getUserProfile} from "@/api/system/user";
import {throttle} from "@/utils";
import {mapGetters} from 'vuex'

export default {
  name: 'ProblemSummary',
  // dicts: ['sys_project_schedule'],
  data() {
    return {
      uploadLoading: false, // 按钮加载
      imgDialogUrl: "",// 预览图链接
      env: process.env.VUE_APP_STATIC_API || '',
      imgDialogVisible: false, // 预览图片的弹框
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: true,
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        content: "",
        image: "",
        workorderId: 0,
        createBy: "", // 创建人
        createTime: "", // 创建时间
        id: null,
        remark: "", // 备注
        updateBy: "",
        updateTime: ""
      },
      // 表单的校验规则
      rules: {
        // province: [
        //   { required: true, message: '请选择省份', trigger: 'change' }
        // ],
        content: [
          {required: true, message: '请输入工作日志', trigger: 'blur'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        workorderId: null,
        createBy: "", // 学校名 *
        province: "", // 省份 *
        startDate: "",
        endDate: "",
        pageNum: 1,
        pageSize: 10,
        pages: 0, // 总页数
        hasNextPage: false, // 还有下一页
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 图片列表
      fileList: []
    }
  },
  props: {
    workorder: {
      type: Object,
      required: true
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  watch: {
    workorder: {
      handler(newV) {
        this.form.workorderId = newV.id
        this.queryParams.workorderId = newV.id
        newV.id && this.getList()
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getUserinfo()
  },
  methods: {
    // 下拉加载
    handleLoad: throttle(function() {
      if(!this.queryParams.hasNextPage) {
        return false
      }
      this.queryParams.pageNum += 1
      this.getList({ isConnect: true })
    }, 2000),
    // 查看图片
    handlePictureCardPreview(url) {
      this.imgDialogUrl = this.env + url
      this.imgDialogVisible = true;
    },
    // 上传全部图片
    async uploadImg() {
      const urlList = (this.fileList ?? []).filter(i => !i.raw).map(i => i.url.replace(this.env, ""))

      const list = (this.fileList ?? []).filter(i => i.raw).map((item) => {
        const formData = new FormData()
        formData.append('file', item.raw)
        return uploadImgApi(formData)
      })

      try {
        this.uploadLoading = true
        const imgList = (await Promise.all(list) ?? []).map(item => item?.fileName ?? "") ?? []
        this.form.image = [...urlList, ...imgList].join(',')
        this.uploadLoading = false
      } catch (e) {
        this.uploadLoading = false
      }
    },
    // 删除图片
    handleRemove(_, fileList) {
      this.fileList = fileList
    },
    // 选中图片
    handleChange(_, fileList) {
      this.fileList = fileList
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList(options) {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        if(options?.isConnect) {
          const list = res.data.list ?? []
          this.tableData = [...this.tableData, ...list]
        } else {
          this.tableData = res.data.list ?? []
        }

        this.total = res.data.total ?? 0
        this.queryParams.pages = res.data.pages ?? 0
        this.queryParams.hasNextPage = res.data.hasNextPage
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {...row}
        this.fileList = ((row.image ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: this.env + item
        }))
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.form = {...this.$options.data().form}
          this.fileList = []
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/newspaper/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `newspaper_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      if (this.form.isImportant === 1 && !(this.form.basis)) {
        this.$notify({
          title: '警告',
          message: '请选择重点依据',
          type: 'warning'
        });
        return false
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {

          try {
            this.uploadLoading = true
            await this.uploadImg()
          } catch (error) {
            this.uploadLoading = false
          }

          this.uploadLoading = false

          if (!this.form.workorderId) {
            this.form.workorderId = +this.$route.query.workorderId
          }

          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        deptId: this.user.deptId,
        userId: this.user.userId,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
      }

      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.fileList = []
        this.dialogVisible = false
        this.$refs['formRef'].resetFields();
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
}

.justify-content {
  justify-content: center;
}

.infinite-list {
  padding: 0;

  .infinite-list-item {
    margin: 8px 0;
    list-style: none;
  }

  .cus_text {
    & > div {
      margin: 10px auto;

      & > span:first-child {
        display: inline-block;
        width: 80px;
        font-weight: bolder;
        text-align: right;
        margin-right: 8px;
      }
    }
  }

  .flex {
    display: flex;
  }

  .items-center {
    align-items: center;
  }

  .flex-1 {
    flex: 1;
  }
}
</style>
